module builder

import time
import os
import v.parser
import v.pref
import v.gen

pub fn (mut b Builder) gen_c(v_files []string) string {
	t0 := time.ticks()
	b.parsed_files = parser.parse_files(v_files, b.table, b.pref, b.global_scope)
	b.parse_imports()
	t1 := time.ticks()
	parse_time := t1 - t0
	b.info('PARSE: ${parse_time}ms')
	//
	b.checker.check_files(b.parsed_files)
	t2 := time.ticks()
	check_time := t2 - t1
	b.info('CHECK: ${check_time}ms')
	b.print_warnings_and_errors()
	// println('starting cgen...')
	// TODO: move gen.cgen() to c.gen()
	res := gen.cgen(b.parsed_files, b.table, b.pref)
	t3 := time.ticks()
	gen_time := t3 - t2
	b.info('C GEN: ${gen_time}ms')
	// println('cgen done')
	// println(res)
	return res
}

pub fn (mut b Builder) build_c(v_files []string, out_file string) {
	b.out_name_c = out_file
	b.info('build_c($out_file)')
	output2 := b.gen_c(v_files)
	mut f := os.create(out_file) or {
		panic(err)
	}
	f.writeln(output2)
	f.close()
	// os.write_file(out_file, b.gen_c(v_files))
}

pub fn (mut b Builder) compile_c() {
	if os.user_os() != 'windows' && b.pref.ccompiler == 'msvc' {
		verror('Cannot build with msvc on ${os.user_os()}')
	}
	// cgen.genln('// Generated by V')
	// println('compile2()')
	if b.pref.is_verbose {
		println('all .v files before:')
		// println(files)
	}
	// v1 compiler files
	// v.add_v_files_to_compile()
	// v.files << v.dir
	// v2 compiler
	// b.set_module_lookup_paths()
	mut files := b.get_builtin_files()
	files << b.get_user_files()
	b.set_module_lookup_paths()
	if b.pref.is_verbose {
		println('all .v files:')
		println(files)
	}
	mut out_name_c := get_vtmp_filename(b.pref.out_name, '.tmp.c')
	if b.pref.is_shared {
		out_name_c = get_vtmp_filename(b.pref.out_name, '.tmp.so.c')
	}
	b.build_c(files, out_name_c)
	b.cc()
}
